package com.ad.aidai.fragments.forget_password;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.ad.aidai.R;
import com.ad.aidai.base.BaseFragment;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.widgets.edittext.ClearEditText;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.fragments.reset_password.ResetPasswordFragment;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 忘记密码
 * <p>
 * Created by rofe on 16/12/18.
 */
public class ForgetPasswordFragment extends BaseFragment implements ForgetPasswordContract.View {

    @BindView(R.id.cet_phone)
    ClearEditText cetPhone;
    @BindView(R.id.verification_code_input)
    EditText verificationCodeInput;
    @BindView(R.id.verification_code_button)
    Button verificationCodeButton;
    @BindView(R.id.btn_check)
    Button btnCheck;

    private ForgetPasswordContract.Presenter mPresenter;
    /**
     * 加载对话框
     */
    private LoadingDialog loadingDialog;

    @Override
    protected void initLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_forget_password, container, false);
    }

    @Override
    protected void initView() {
        //对于刚跳到一个新的界面就要弹出软键盘的情况上述代码可能由于界面为加载完全而无法弹出软键盘。
        //此时应该适当的延迟弹出软键盘如998毫秒（保证界面的数据加载完成）
        verificationCodeInput.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                openSoftInput(verificationCodeInput);
            }
        }, 500);
    }

    @Override
    protected void initData() {
        new ForgetPasswordPresenter(mContext, this).subscribe();

        //进入界面,先加载保存过的手机号,如果没有则会显示为空
        mPresenter.loadPhone();
    }

    @OnClick({R.id.iv_back, R.id.btn_check, R.id.verification_code_button, R.id.rl_forget_password_view})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_check:
                mPresenter.verifyPhone(cetPhone.getText().toString(), verificationCodeInput.getText().toString());
                break;
            case R.id.verification_code_button:
                mPresenter.sendVerificationCode(cetPhone.getText().toString());
                break;
            case R.id.iv_back:
                back();
                break;
            case R.id.rl_forget_password_view:
                break;
        }
    }

    private void back(){
        if (cetPhone.isFocused()) {
            closeSoftInput(cetPhone);
        } else if (verificationCodeInput.isFocused()) {
            closeSoftInput(verificationCodeInput);
        }
        getFragmentManager().popBackStack();
    }

    /**
     * 关闭软键盘
     *
     * @param view 对应的EditText
     */
    public void closeSoftInput(View view) {
        InputMethodManager inputManager = (InputMethodManager) mActivity.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 打开软键盘
     *
     * @param view 对应的EditText
     */
    public void openSoftInput(View view) {
        InputMethodManager inputManager = (InputMethodManager) mActivity.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(view, 0);
    }

    @Override
    public void setPresenter(ForgetPasswordContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void setPhoneNumber(String phone) {
        cetPhone.setText(phone);
    }

    @Override
    public void setVCButtonClickable(boolean isClick) {
        if (!isClick) {
            verificationCodeButton.setClickable(false);
            verificationCodeButton.setTextColor(Color.WHITE);
            verificationCodeButton.setBackground(ContextCompat.getDrawable(mContext, R.drawable
                    .btn_get_code_after_shape));
        } else {
            verificationCodeButton.setClickable(true);
            verificationCodeButton.setText("发送验证码");
            verificationCodeButton.setTextColor(ContextCompat.getColor(mContext, R.color.register_verification_button));
            verificationCodeButton.setBackground(ContextCompat.getDrawable(mContext, R.drawable.btn_get_code_selector));
        }

    }

    @Override
    public void showVerficationCodeCountDown(String time) {
        verificationCodeButton.setText(time);
    }

    @Override
    public void showLoading() {
        //显示加载对话框
        loadingDialog = new LoadingDialog(mContext);
        loadingDialog.setLoadingText("验证中...")
                .setFailedText("验证失败")
                .setSuccessText("验证成功")
                .show();
    }

    @Override
    public void closeLoading(boolean success) {
        if (loadingDialog != null) {
            if (success) {
                loadingDialog.loadSuccess();
            } else {
                loadingDialog.loadFailed();
            }
        }
    }

    @Override
    public void verifySuccess(final String token) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (loadingDialog != null && loadingDialog.isShowing()) {

                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        openResetPassword(token);
                    }
                });
            }
        }).start();
    }

    private void openResetPassword(String token){
        ResetPasswordFragment resetPasswordFragment = new ResetPasswordFragment();
        Bundle bundle = new Bundle();
        bundle.putString("phone", cetPhone.getText().toString());
        bundle.putString("token", token);
        resetPasswordFragment.setArguments(bundle);
        getFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                        .fragment_slide_left_exit)
                .add(android.R.id.content, resetPasswordFragment, "resetPassword")
                .addToBackStack("resetPassword")
                .commit();
    }

    @Override
    protected void subscribeEvents() {
        addSubscription(RxBus.getInstance()
                .toObservable()
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        if (o instanceof CommonEvent) {
                            CommonEvent event = (CommonEvent) o;
                            switch (event.getEvent()) {
                                case CommonEvent.RESET_PASSWORD_FINISHED:
                                    mPresenter.savePhone(cetPhone.getText().toString());
                                    RxBus.getInstance().postEvent
                                            (new CommonEvent<>(CommonEvent.RESET_PHONE_FINISHED));
                                    back();
                                    break;
                            }
                        }
                    }
                })
                .subscribe(RxBus.defaultSubscriber())
        );
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.unSubscribe();
    }

    @Override
    public boolean onActivityBackPressed() {
        return true;
    }
}
